package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> querylist() {
     //判断redis中有没有查出来的这个值,如果没有去查数据库，如果有将其保存到redis中（使用Set方式）
        String key = "cache:shoptype:list";
        Set<String> members = stringRedisTemplate.opsForSet().members(key);
        if (members != null && members.size() > 0) {
            //将set集合转换为list集合
            List<String> list = members.stream().toList();
            //将list集合转换为对象
            List<ShopType> shopTypes = JSONUtil.toList(list.toString(), ShopType.class);
            return shopTypes;
        }
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        //判断是否存在于数据库，若不存在返回错误，存在则存进redis中
        if (shopTypes == null) {
            return null;
        }
        for (ShopType shopType : shopTypes) {
            stringRedisTemplate.opsForSet().add(key, JSONUtil.toJsonStr(shopType));
        }
        return shopTypes;

    }
}
